package com.aizuda.boot.modules.business.permission.provider.impl;

import com.aizuda.boot.modules.business.contract.dto.SingleResponse;
import com.aizuda.boot.modules.business.contract.dto.UserInfo;
import com.aizuda.boot.modules.common.constant.enums.ResponseCodeEnum;
import com.aizuda.boot.modules.business.contract.util.AuthUtil;
import com.aizuda.boot.modules.business.permission.domain.entity.RoleDataIsolationEntity;
import com.aizuda.boot.modules.business.permission.domain.entity.RoleEmployeeScopeRelEntity;
import com.aizuda.boot.modules.business.permission.domain.entity.RoleEntity;
import com.aizuda.boot.modules.business.permission.domain.entity.RolePermissionEntity;
import com.aizuda.boot.modules.business.permission.domain.request.*;
import com.aizuda.boot.modules.business.permission.domain.response.*;
import com.aizuda.boot.modules.business.permission.provider.RoleProvider;
import com.aizuda.boot.modules.business.permission.service.*;
import com.aizuda.boot.modules.common.constant.enums.*;
import com.aizuda.boot.modules.system.entity.*;
import com.aizuda.boot.modules.system.service.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Description: 角色业务
 *
 * @author duanyao
 * @date 2021-11-27 18:07
 */
@Service
@Slf4j
public class RoleProviderImpl implements RoleProvider {

    @Autowired
    private RoleService roleService;

    @Autowired
    private RoleDataIsolationService roleDataIsolationService;

    @Autowired
    private RolePermissionService rolePermissionService;

    @Autowired
    private RoleEmployeeScopeRelService roleEmployeeScopeRelService;

    @Resource
    private ISysRoleService sysRoleService;

    @Resource
    private ISysUserRoleService sysUserRoleService;

    @Resource
    private ISysUserService sysUserService;

    @Resource
    private ISysUserDepartmentService sysUserDepartmentService;

    @Resource
    private ISysDepartmentService sysDepartmentService;

    /**
     * 修改角色状态
     *
     * @param roleId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public SingleResponse<Void> enableRole(Long roleId) {
        if (roleId == null) {
            return SingleResponse.failure(ResponseCodeEnum.PARAMETER_ERROR.getCode(), ResponseCodeEnum.PARAMETER_ERROR.getMsg());
        }
        UserInfo currentUser = AuthUtil.getCurrentUser();
        if (Objects.isNull(currentUser) || currentUser.getUserId() == null) {
            return SingleResponse.failure(ResponseCodeEnum.NOT_LOGGED.getCode(), ResponseCodeEnum.NOT_LOGGED.getMsg());
        }
        RoleEntity role = roleService.getById(roleId);

        if (Objects.isNull(role)) {
            return SingleResponse.failure(ResponseCodeEnum.DATA_NOT_FOUND.getCode(), ResponseCodeEnum.DATA_NOT_FOUND.getMsg());
        }
        //修改状态
        role.setEnable(role.getEnable().equals(Boolean.FALSE));
        role.setGmtModified(new Date());
        role.setModifiedUser(Long.valueOf(currentUser.getUserId()));
        role.setModifiedUserName(currentUser.getUsername());
        roleService.updateById(role);
        return SingleResponse.success();
    }

    @Override
    public SingleResponse<RoleShowVO> getRole(Long roleId) {
        if (roleId == null) {
            return SingleResponse.failure(ResponseCodeEnum.PARAMETER_ERROR.getCode(), ResponseCodeEnum.PARAMETER_ERROR.getMsg());
        }
        SysRole role = sysRoleService.getById(roleId);
        if (Objects.isNull(role)) {
            return SingleResponse.failure(ResponseCodeEnum.DATA_NOT_FOUND.getCode(), ResponseCodeEnum.DATA_NOT_FOUND.getMsg());
        }

        // 创建对象
        RoleShowVO roleShowVO = new RoleShowVO();
        roleShowVO.setRoleId(role.getId());
        roleShowVO.setRoleName(role.getName());
        roleShowVO.setRoleCode(role.getAlias());
        roleShowVO.setDescription(role.getRemark());

        List<RolePermissionEntity> list = rolePermissionService.list(new LambdaQueryWrapper<RolePermissionEntity>()
                .eq(RolePermissionEntity::getRoleId, roleId));
        List<String> checkedKeys = list.stream()
                .filter(item -> item != null && item.getPermissionCode() != null)
                .map(RolePermissionEntity::getPermissionCode).collect(Collectors.toList());
        BaseInfo baseInfo = new BaseInfo();
        baseInfo.setCheckedKeys(checkedKeys);
        baseInfo.setSelectValues(list.stream()
                .filter(item -> item != null && item.getPermissionCode() != null && item.getPermissionValue() != null)
                .collect(Collectors.toMap(RolePermissionEntity::getPermissionCode, RolePermissionEntity::getPermissionValue)));
        roleShowVO.setBaseInfo(baseInfo);

        List<DataPermissionShowVO> permissionList = roleDataIsolationService.list(new LambdaQueryWrapper<RoleDataIsolationEntity>()
                        .eq(RoleDataIsolationEntity::getRoleId, roleId)).stream()
                .filter(item -> item != null)
                .map(item -> {
                    DataPermissionShowVO dataPermissionShowVO = new DataPermissionShowVO();
                    dataPermissionShowVO.setId(item.getPermissionId());
                    dataPermissionShowVO.setName(item.getPermissionName());
                    dataPermissionShowVO.setEnabled(item.getPermissionStatus() != null && item.getPermissionStatus().equals(PermissionStatusType.ENABLE));
                    dataPermissionShowVO.setContent(item.getContent());
                    dataPermissionShowVO.setValidType(item.getValidityType());
                    RawVo rawVo = new RawVo();
                    rawVo.setName(item.getPermissionName());
                    rawVo.setValidType(item.getValidityType());
                    rawVo.setDataType(item.getDataType());
                    if (DataType.CONTRACT.equals(item.getDataType()) && item.getContractScope() != null) {
                        rawVo.setContractScope(item.getContractScope());
                    }
                    if (DataType.NEGOTIATION.equals(item.getDataType()) && item.getContractScope() != null) {
                        rawVo.setNegotiationScope(item.getContractScope());
                    }

                    if (item.getValidityType() != null && item.getValidityType().equals(ValidityType.FIXED_DATE)) {
                        List<Date> dates = new ArrayList<>();
                        dates.add(item.getValidityStartDate());
                        dates.add(item.getValidityEndDate());
                        rawVo.setValidRange(dates);
                        dataPermissionShowVO.setValidRange(dates);
                    }
                    dataPermissionShowVO.setRaw(rawVo);
                    return dataPermissionShowVO;
                }).collect(Collectors.toList());
        roleShowVO.setDataPermissions(permissionList != null ? permissionList : new ArrayList<>());

        // 获取角色成员信息
        List<SysUserRole> roleEmployees = sysUserRoleService.list(new LambdaQueryWrapper<SysUserRole>()
                .eq(SysUserRole::getRoleId, roleId));
        Map<Long, SysDepartment> employeeDepartmentMap = null;
        if (!CollectionUtils.isEmpty(roleEmployees)) {
            List<Long> employeeIds = roleEmployees
                    .stream()
                    .filter(re -> re != null && re.getUserId() != null)
                    .map(SysUserRole::getUserId)
                    .collect(Collectors.toList());

            // 如果没有有效的员工ID，则跳过后续处理
            if (CollectionUtils.isEmpty(employeeIds)) {
                roleShowVO.setMembers(new ArrayList<>());
                return SingleResponse.of(roleShowVO);
            }

            // 获取员工信息
            List<SysUser> employees = sysUserService.list(new LambdaQueryWrapper<SysUser>()
                    .in(SysUser::getId, employeeIds));
            Map<Long, SysUser> employeeMap = employees.stream()
                    .filter(emp -> emp != null && emp.getId() != null)
                    .collect(Collectors.toMap(SysUser::getId, item -> item));

            // 获取部门信息
            List<SysUserDepartment> departmentEmployeeRelEntities = sysUserDepartmentService.list(new LambdaQueryWrapper<SysUserDepartment>()
                    .in(SysUserDepartment::getUserId, employeeIds));
            // 获取员工与部门映射（如果员工属于多个部门，保留第一个）
            Map<Long, Long> ids = departmentEmployeeRelEntities.stream()
                    .filter(rel -> rel != null && rel.getUserId() != null && rel.getDepartmentId() != null)
                    .collect(Collectors.toMap(
                            SysUserDepartment::getUserId,
                            SysUserDepartment::getDepartmentId,
                            (existing, replacement) -> existing // 当有重复key时，保留现有值
                    ));
            List<SysUserDepartment> departments = departmentEmployeeRelEntities.stream()
                    .filter(Objects::nonNull)
                    .distinct().collect(Collectors.toList());
            List<Long> departmentIds = departments.stream()
                    .filter(dept -> dept != null && dept.getDepartmentId() != null)
                    .map(SysUserDepartment::getDepartmentId).distinct()
                    .collect(Collectors.toList());
            Map<Long, SysDepartment> map;
            if (!CollectionUtils.isEmpty(departmentIds)) {
                map = sysDepartmentService.list(new LambdaQueryWrapper<SysDepartment>().in(SysDepartment::getId, departmentIds))
                        .stream()
                        .filter(dept -> dept != null && dept.getId() != null)
                        .collect(Collectors.toMap(SysDepartment::getId, item -> item));
                employeeDepartmentMap = employeeIds.stream()
                        .filter(id -> id != null && ids.containsKey(id) && ids.get(id) != null && map.containsKey(ids.get(id)))
                        .collect(Collectors.toMap(item -> item, id -> map.get(ids.get(id))));
            }

            ArrayList<RoleEmployeeShowVo> roleEmployeeShowVos = new ArrayList<>();
            for (SysUserRole roleEmployee : roleEmployees) {
                if (roleEmployee == null) {
                    continue;
                }
                RoleEmployeeShowVo roleEmployeeShowVo = new RoleEmployeeShowVo();
                roleEmployeeShowVo.setId(roleEmployee.getId());
                roleEmployeeShowVo.setEmployeeId(roleEmployee.getUserId());
                roleEmployeeShowVo.setDepartmentAll(roleEmployee.getDepartmentAll());
                roleEmployeeShowVo.setCityAll(roleEmployee.getCityAll());
                roleEmployeeShowVo.setCity(roleEmployee.getCity());

                if (null != roleEmployee.getDepartmentAll() && !roleEmployee.getDepartmentAll()) {
                    try {
                        roleEmployeeShowVo.setDepartment(Arrays.stream(roleEmployee.getDepartment().split(","))
                                .filter(dept -> dept != null && !dept.trim().isEmpty())
                                .map(Long::parseLong).collect(Collectors.toList()));
                    } catch (NumberFormatException e) {
                        log.warn("解析部门ID时发生错误: {}", roleEmployee.getDepartment(), e);
                    }
                }

                // 添加员工信息
                if (roleEmployee.getUserId() != null && employeeMap.containsKey(roleEmployee.getUserId())) {
                    SysUser employee = employeeMap.get(roleEmployee.getUserId());
                    if (employee != null) {
                        roleEmployeeShowVo.setEmployeeName(employee.getNickName());
                        roleEmployeeShowVo.setAvatar(employee.getAvatar());
                        roleEmployeeShowVo.setId(employee.getId());
                    }
                }

                // 添加部门信息
                if (employeeDepartmentMap != null && roleEmployee.getUserId() != null
                        && employeeDepartmentMap.containsKey(roleEmployee.getUserId())) {
                    SysDepartment department = employeeDepartmentMap.get(roleEmployee.getUserId());
                    if (department != null) {
                        roleEmployeeShowVo.setDeptName(department.getName());
                    }
                }

                //  添加部门
                if (!CollectionUtils.isEmpty(roleEmployeeShowVo.getDepartment())) {
                    List<String> collect = sysDepartmentService.listByIds(roleEmployeeShowVo.getDepartment()).stream()
                            .filter(dept -> dept != null && dept.getName() != null)
                            .map(SysDepartment::getName).collect(Collectors.toList());
                    roleEmployeeShowVo.setDepartmentName(String.join(",", collect));
                }

                roleEmployeeShowVos.add(roleEmployeeShowVo);
            }
            roleShowVO.setMembers(roleEmployeeShowVos);
        } else {
            // 确保members不为null
            roleShowVO.setMembers(new ArrayList<>());
        }

        return SingleResponse.of(roleShowVO);
    }

    /**
     * 新增角色
     *
     * @param addRoleVO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public SingleResponse<Void> addRole(AddRoleVO addRoleVO) {
        UserInfo currentUser = AuthUtil.getCurrentUser();
        if (Objects.isNull(currentUser.getEmployeeId())) {
            return SingleResponse.failure(ResponseCodeEnum.NOT_LOGGED.getCode(), ResponseCodeEnum.NOT_LOGGED.getMsg());
        }
        log.info("===================添加角色=========");
        if (Objects.isNull(addRoleVO)) {
            return SingleResponse.failure(ResponseCodeEnum.PARAMETER_ERROR.getCode(), ResponseCodeEnum.PARAMETER_ERROR.getMsg());
        }
        if (addRoleVO.getRoleName() == null) {
            return SingleResponse.failure(ResponseCodeEnum.PARAMETER_ERROR.getCode(), ResponseCodeEnum.PARAMETER_ERROR.getMsg());
        }
        if (Objects.isNull(addRoleVO.getBaseInfo())) {
            return SingleResponse.failure(ResponseCodeEnum.PARAMETER_ERROR.getCode(), ResponseCodeEnum.PARAMETER_ERROR.getMsg());
        }
        long count = sysRoleService.count(new LambdaQueryWrapper<SysRole>()
                .eq(SysRole::getName, addRoleVO.getRoleName()));
        if (count > 0) {
            return SingleResponse.failure(ResponseCodeEnum.DATA_ALREADY_EXISTS.getCode(), "角色名称已存在");
        }
        SysRole roleEntity = new SysRole();
        roleEntity.setName(addRoleVO.getRoleName());
        roleEntity.setRemark(addRoleVO.getDescription());
        roleEntity.setStatus(1);
        roleEntity.setAlias(generateRandomAlphaString(8));
        sysRoleService.save(roleEntity);

        if (!CollectionUtils.isEmpty(addRoleVO.getBaseInfo().getCheckedKeys())) {
            ArrayList<RolePermissionEntity> rolePermissionEntities = new ArrayList<>();
            List<String> checkedKeys = addRoleVO.getBaseInfo().getCheckedKeys();
            Map<String, String> selectValues = addRoleVO.getBaseInfo().getSelectValues();
            for (String checkedKey : checkedKeys) {
                RolePermissionEntity rolePermissionEntity = new RolePermissionEntity();
                rolePermissionEntity.setRoleId(roleEntity.getId());
                rolePermissionEntity.setPermissionCode(checkedKey);
                if (selectValues.containsKey(checkedKey)) {
                    rolePermissionEntity.setPermissionValue(selectValues.get(checkedKey));
                }
                rolePermissionEntities.add(rolePermissionEntity);
            }
            rolePermissionService.saveBatch(rolePermissionEntities);
        }
        // 添加数据权限
        if (!CollectionUtils.isEmpty(addRoleVO.getDataPermissions())) {
            ArrayList<RoleDataIsolationEntity> roleDataIsolationEntities = new ArrayList<>();
            List<DataPermission> permissionList = addRoleVO.getDataPermissions();
            // 判断是否有名字相同的权限
            List<String> PermissionNameList = permissionList.stream().map(DataPermission::getName).collect(Collectors.toList());
            List<String> existName = roleDataIsolationService.list(new LambdaQueryWrapper<RoleDataIsolationEntity>()
                            .in(RoleDataIsolationEntity::getPermissionName, PermissionNameList))
                    .stream().map(RoleDataIsolationEntity::getPermissionName).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(existName)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                String collect = existName.stream().collect(Collectors.joining(","));
                return SingleResponse.failure(ResponseCodeEnum.DATA_ALREADY_EXISTS.getCode(), "权限：" + collect + "已经存在");
            }
            // 保存权限
            for (DataPermission permission : permissionList) {
                RoleDataIsolationEntity roleDataIsolationEntity = new RoleDataIsolationEntity();
                roleDataIsolationEntity.setPermissionName(permission.getName());
                roleDataIsolationEntity.setRoleId(roleEntity.getId());
                roleDataIsolationEntity.setValidityType(permission.getValidType());

                // 权限的状态
                roleDataIsolationEntity.setPermissionStatus(permission.getEnabled() ? PermissionStatusType.ENABLE : PermissionStatusType.DISABLE);
                if (permission.getValidType().equals(ValidityType.FIXED_DATE)) {
                    roleDataIsolationEntity.setValidityStartDate(permission.getValidRange().get(0));
                    roleDataIsolationEntity.setValidityEndDate(permission.getValidRange().get(1));
                    if (permission.getEnabled() && permission.getValidRange().get(0).after(new Date())) {
                        roleDataIsolationEntity.setPermissionStatus(PermissionStatusType.UN_ENABLE);
                    }
                    if (permission.getEnabled() && permission.getValidRange().get(1).before(new Date())) {
                        roleDataIsolationEntity.setPermissionStatus(PermissionStatusType.EXPIRED);
                    }
                }
                // 权限的数据类型
                roleDataIsolationEntity.setDataType(permission.getRaw().getDataType());
                if (DataType.CONTRACT.equals(permission.getRaw().getDataType())) {
                    roleDataIsolationEntity.setContractScope(permission.getRaw().getContractScope());
                    roleDataIsolationEntity.setUseCustomCondition(permission.getRaw().getContractScope().equals(ContractScopeTypeEnums.CUSTOM));
                }
                if (DataType.NEGOTIATION.equals(permission.getRaw().getDataType())) {
                    roleDataIsolationEntity.setContractScope(permission.getRaw().getNegotiationScope());
                    roleDataIsolationEntity.setUseCustomCondition(permission.getRaw().getNegotiationScope().equals(ContractScopeTypeEnums.CUSTOM));
                }
                roleDataIsolationEntity.setContent(permission.getContent());
                roleDataIsolationEntities.add(roleDataIsolationEntity);
            }
            roleDataIsolationService.saveBatch(roleDataIsolationEntities);
        }
        if (!CollectionUtils.isEmpty(addRoleVO.getMembers())) {
            ArrayList<SysUserRole> roleEmployeeScopeRelEntities = new ArrayList<>();
            for (RoleEmployeeVo member : addRoleVO.getMembers()) {
                SysUserRole roleEmployeeScopeRelEntity = new SysUserRole();
                roleEmployeeScopeRelEntity.setRoleId(roleEntity.getId());
                if (member.getDepartmentAll()) {
                    roleEmployeeScopeRelEntity.setDepartmentAll(true);
                } else {
                    roleEmployeeScopeRelEntity.setDepartmentAll(false);
                    String collect = member.getDepartment().stream().map(String::valueOf).collect(Collectors.joining(","));
                    roleEmployeeScopeRelEntity.setDepartment(collect);
                }
                roleEmployeeScopeRelEntity.setCityAll(member.getCityAll());
                roleEmployeeScopeRelEntity.setUserId(member.getEmployeeId());
                roleEmployeeScopeRelEntity.setCity(member.getCity());
                roleEmployeeScopeRelEntities.add(roleEmployeeScopeRelEntity);
            }
            sysUserRoleService.saveBatch(roleEmployeeScopeRelEntities);
        }
        return SingleResponse.success();
    }

    @Override
    public SingleResponse<IPage<PageRoleResponseVO>> pageRole(IPage<PageRoleResponseVO> page, PageRoleVO pageRoleVO) {
        UserInfo currentUser = AuthUtil.getCurrentUser();
        if (Objects.isNull(currentUser.getEmployeeId())) {
            return SingleResponse.failure(ResponseCodeEnum.NOT_LOGGED.getCode(), ResponseCodeEnum.NOT_LOGGED.getMsg());
        }
        log.info("======================分页查询角色信息==============");
        if (Objects.isNull(page) || page.getCurrent() < 1 || page.getSize() < 1) {
            return SingleResponse.failure(ResponseCodeEnum.PARAMETER_ERROR.getCode(), ResponseCodeEnum.PARAMETER_ERROR.getMsg());
        }
        List<Long> roleIdList = null;
        // 查询用户所处于的角色
        if (!CollectionUtils.isEmpty(pageRoleVO.getUserIds())) {
            roleIdList = sysUserRoleService.list(new LambdaQueryWrapper<SysUserRole>()
                            .select(SysUserRole::getRoleId).in(SysUserRole::getUserId, pageRoleVO.getUserIds()))
                    .stream().map(SysUserRole::getRoleId).distinct().collect(Collectors.toList());
            if (CollectionUtils.isEmpty(roleIdList)) {
                return SingleResponse.of(page);
            }
        }
        page = sysRoleService.pageRole(page, pageRoleVO, roleIdList);
        return SingleResponse.of(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SingleResponse<Void> updateRole(UpdateRoleVO updateRoleVO) {
        UserInfo currentUser = AuthUtil.getCurrentUser();
        if (Objects.isNull(currentUser.getEmployeeId())) {
            return SingleResponse.failure(ResponseCodeEnum.NOT_LOGGED.getCode(), ResponseCodeEnum.NOT_LOGGED.getMsg());
        }
        if (Objects.isNull(updateRoleVO)) {
            return SingleResponse.failure(ResponseCodeEnum.PARAMETER_ERROR.getCode(), ResponseCodeEnum.PARAMETER_ERROR.getMsg());
        }
        if (Objects.isNull(updateRoleVO.getRoleId())) {
            return SingleResponse.failure(ResponseCodeEnum.PARAMETER_ERROR.getCode(), ResponseCodeEnum.PARAMETER_ERROR.getMsg());
        }
        long count = sysRoleService.count(new LambdaQueryWrapper<SysRole>()
                .ne(SysRole::getId, updateRoleVO.getRoleId())
                .eq(SysRole::getName, updateRoleVO.getRoleName()));
        if (count > 0) {
            return SingleResponse.failure(ResponseCodeEnum.DATA_ALREADY_EXISTS.getCode(), "角色名称已存在");
        }
        SysRole roleEntity = sysRoleService.getById(updateRoleVO.getRoleId());
        if (Objects.isNull(roleEntity)) {
            return SingleResponse.failure(ResponseCodeEnum.DATA_NOT_FOUND.getCode(), "角色不存在");
        }
        roleEntity.setName(updateRoleVO.getRoleName());
        roleEntity.setRemark(updateRoleVO.getDescription());
        sysRoleService.updateById(roleEntity);

        rolePermissionService.remove(new LambdaQueryWrapper<RolePermissionEntity>().eq(RolePermissionEntity::getRoleId, updateRoleVO.getRoleId()));
        if (!CollectionUtils.isEmpty(updateRoleVO.getBaseInfo().getCheckedKeys())) {
            ArrayList<RolePermissionEntity> rolePermissionEntities = new ArrayList<>();
            List<String> checkedKeys = updateRoleVO.getBaseInfo().getCheckedKeys();
            Map<String, String> selectValues = updateRoleVO.getBaseInfo().getSelectValues();
            for (String checkedKey : checkedKeys) {
                RolePermissionEntity rolePermissionEntity = new RolePermissionEntity();
                rolePermissionEntity.setRoleId(roleEntity.getId());
                rolePermissionEntity.setPermissionCode(checkedKey);
                if (selectValues.containsKey(checkedKey)) {
                    rolePermissionEntity.setPermissionValue(selectValues.get(checkedKey));
                }
                rolePermissionEntities.add(rolePermissionEntity);
            }
            rolePermissionService.saveBatch(rolePermissionEntities);
        }

        roleDataIsolationService.remove(new LambdaQueryWrapper<RoleDataIsolationEntity>().eq(RoleDataIsolationEntity::getRoleId, updateRoleVO.getRoleId()));
        if (!CollectionUtils.isEmpty(updateRoleVO.getDataPermissions())) {
            List<String> collect = updateRoleVO.getDataPermissions().stream().map(DataPermissionShowVO::getName).collect(Collectors.toList());
            long count1 = roleDataIsolationService.count(new LambdaQueryWrapper<RoleDataIsolationEntity>()
                    .in(RoleDataIsolationEntity::getPermissionName, collect));
            if (count1 > 0) {
                return SingleResponse.failure(ResponseCodeEnum.DATA_ALREADY_EXISTS.getCode(), "权限已存在");
            }
            ArrayList<RoleDataIsolationEntity> roleDataIsolationEntities = new ArrayList<>();
            List<DataPermissionShowVO> dataPermissions = updateRoleVO.getDataPermissions();
            for (DataPermissionShowVO dataPermission : dataPermissions) {
                RoleDataIsolationEntity roleDataIsolation = new RoleDataIsolationEntity();
                if (dataPermission.getId() != null) {
                    roleDataIsolation.setPermissionId(dataPermission.getId());
                } else {
                    roleDataIsolation.setPermissionId(null);
                }
                roleDataIsolation.setPermissionName(dataPermission.getName());
                roleDataIsolation.setRoleId(roleEntity.getId());
                roleDataIsolation.setValidityType(dataPermission.getValidType());

                //  权限状态
                roleDataIsolation.setPermissionStatus(dataPermission.getEnabled() ? PermissionStatusType.ENABLE : PermissionStatusType.DISABLE);
                if (dataPermission.getValidType().equals(ValidityType.FIXED_DATE)) {
                    roleDataIsolation.setValidityStartDate(dataPermission.getValidRange().get(0));
                    roleDataIsolation.setValidityEndDate(dataPermission.getValidRange().get(1));
                    if (dataPermission.getEnabled() && dataPermission.getValidRange().get(0).after(new Date())) {
                        roleDataIsolation.setPermissionStatus(PermissionStatusType.UN_ENABLE);
                    }
                    if (dataPermission.getEnabled() && dataPermission.getValidRange().get(1).before(new Date())) {
                        roleDataIsolation.setPermissionStatus(PermissionStatusType.EXPIRED);
                    }
                }
                roleDataIsolation.setDataType(dataPermission.getRaw().getDataType());
                if (DataType.CONTRACT.equals(dataPermission.getRaw().getDataType())) {
                    roleDataIsolation.setContractScope(dataPermission.getRaw().getContractScope());
                    roleDataIsolation.setUseCustomCondition(dataPermission.getRaw().getContractScope().equals(ContractScopeTypeEnums.CUSTOM));
                }
                if (DataType.NEGOTIATION.equals(dataPermission.getRaw().getDataType())) {
                    roleDataIsolation.setContractScope(dataPermission.getRaw().getNegotiationScope());
                    roleDataIsolation.setUseCustomCondition(dataPermission.getRaw().getNegotiationScope().equals(ContractScopeTypeEnums.CUSTOM));
                }

                roleDataIsolation.setContent(dataPermission.getContent());
                roleDataIsolationEntities.add(roleDataIsolation);

            }
            roleDataIsolationService.saveOrUpdateBatch(roleDataIsolationEntities);
        }

        sysUserRoleService.remove(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getRoleId, updateRoleVO.getRoleId()));
        if (!CollectionUtils.isEmpty(updateRoleVO.getMembers())) {
            ArrayList<SysUserRole> roleEmployeeScopeRelEntities = new ArrayList<>();
            for (RoleEmployeeShowVo member : updateRoleVO.getMembers()) {
                SysUserRole roleEmployeeScopeRelEntity = new SysUserRole();
                roleEmployeeScopeRelEntity.setUserId(member.getEmployeeId());
                roleEmployeeScopeRelEntity.setDepartmentAll(member.getDepartmentAll());
                if (!member.getDepartmentAll()) {
                    String collect = member.getDepartment().stream().map(String::valueOf).collect(Collectors.joining(","));
                    roleEmployeeScopeRelEntity.setDepartment(collect);
                }
                roleEmployeeScopeRelEntity.setCityAll(member.getCityAll());
                roleEmployeeScopeRelEntity.setCity(member.getCity());
                roleEmployeeScopeRelEntity.setRoleId(roleEntity.getId());
                roleEmployeeScopeRelEntities.add(roleEmployeeScopeRelEntity);
            }
            sysUserRoleService.saveBatch(roleEmployeeScopeRelEntities);
        }
        return SingleResponse.success();
    }

    @Override
    public SingleResponse<List<RoleShowVO>> getCurrentRole() {
        UserInfo currentUser = AuthUtil.getCurrentUser();
        if (Objects.isNull(currentUser) || Objects.isNull(currentUser.getEmployeeId())) {
            return SingleResponse.failure(ResponseCodeEnum.NOT_LOGGED.getCode(), ResponseCodeEnum.NOT_LOGGED.getMsg());
        }

        List<RoleEmployeeScopeRelEntity> roleList = roleEmployeeScopeRelService.list(new LambdaQueryWrapper<RoleEmployeeScopeRelEntity>()
                .eq(RoleEmployeeScopeRelEntity::getEmployeeId, currentUser.getEmployeeId()));
        List<RoleShowVO> roleShowVOS = roleList.stream().map(roleEmployeeScopeRelEntity -> {
            RoleShowVO roleShowVO = new RoleShowVO();
            RoleEntity roleEntity = roleService.getById(roleEmployeeScopeRelEntity.getRoleId());
            BeanUtils.copyProperties(roleEntity, roleShowVO);
            return roleShowVO;
        }).collect(Collectors.toList());
        return SingleResponse.of(roleShowVOS);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SingleResponse<Void> deleteRole(Long roleId) {
        // 1. 参数校验
        if (Objects.isNull(roleId)) {
            return SingleResponse.failure(ResponseCodeEnum.PARAMETER_ERROR.getCode(), ResponseCodeEnum.PARAMETER_ERROR.getMsg());
        }

        // 2. 检查角色是否存在
        SysRole roleEntity = sysRoleService.getById(roleId);
        if (Objects.isNull(roleEntity)) {
            return SingleResponse.failure(ResponseCodeEnum.DATA_NOT_FOUND.getCode(), "角色不存在");
        }

        // 4. 检查角色是否有关联的员工
        long memberCount = sysUserRoleService.count(new LambdaQueryWrapper<SysUserRole>()
                .eq(SysUserRole::getRoleId, roleId));
        if (memberCount > 0) {
            return SingleResponse.failure(ResponseCodeEnum.OPERATION_NOT_ALLOWED.getCode(), "该角色下还有关联的员工，无法删除");
        }

        // 5. 删除角色相关数据
        // 删除角色权限关联
        rolePermissionService.remove(new LambdaQueryWrapper<RolePermissionEntity>().eq(RolePermissionEntity::getRoleId, roleId));

        // 删除数据权限
        roleDataIsolationService.remove(new LambdaQueryWrapper<RoleDataIsolationEntity>().eq(RoleDataIsolationEntity::getRoleId, roleId));

        // 6. 删除角色
        boolean result = sysRoleService.removeById(roleId);
        if (!result) {
            return SingleResponse.failure(ResponseCodeEnum.ERROR.getCode(), "删除角色失败");
        }
        return SingleResponse.success();
    }

    @Override
    public SingleResponse<List<Map<String, String>>> getRoleListByType(QueryRoleListVo queryRoleListVo) {
        List<SysRole> roleEntities = sysRoleService.list(new LambdaQueryWrapper<SysRole>()
                .eq(SysRole::getStatus, 1));
        List<Map<String, String>> collect = roleEntities.stream().map(roleEntity -> {
            Map<String, String> map = new HashMap<>();
            map.put("label", roleEntity.getName());
            map.put("value", roleEntity.getId().toString());
            return map;
        }).collect(Collectors.toList());
        return SingleResponse.of(collect);
    }

    @Override
    public SingleResponse<RoleBasicVO> getRoleBasicInfo(Long roleId) {
        if (roleId == null) {
            return SingleResponse.failure(ResponseCodeEnum.PARAMETER_ERROR.getCode(), ResponseCodeEnum.PARAMETER_ERROR.getMsg());
        }
        SysRole roleEntity = sysRoleService.getById(roleId);
        if (Objects.isNull(roleEntity)) {
            return SingleResponse.failure(ResponseCodeEnum.DATA_NOT_FOUND.getCode(), ResponseCodeEnum.DATA_NOT_FOUND.getMsg());
        }
        RoleBasicVO roleBasicVO = new RoleBasicVO();
        roleBasicVO.setId(roleEntity.getId());
        roleBasicVO.setRoleName(roleEntity.getName());
        roleBasicVO.setRoleCode(roleEntity.getAlias());
        roleBasicVO.setDescription(roleEntity.getRemark());
        roleBasicVO.setSort(roleEntity.getSort());
        roleBasicVO.setEnable(roleEntity.getStatus() == 1);
        return SingleResponse.of(roleBasicVO);
    }

    @Override
    public SingleResponse<OwnPermissionVO> getCurrentPermission() {
        UserInfo currentUser = AuthUtil.getCurrentUser();
        if (Objects.isNull(currentUser.getEmployeeId()) || Objects.isNull(currentUser.getSysTenantKey())) {
            return SingleResponse.failure(ResponseCodeEnum.NOT_LOGGED.getCode(), ResponseCodeEnum.NOT_LOGGED.getMsg());
        }

        // 获取当前用户的角色
        List<SysUserRole> userRoles = sysUserRoleService.list(new LambdaQueryWrapper<SysUserRole>()
                .eq(SysUserRole::getUserId, currentUser.getEmployeeId()));

        if (CollectionUtils.isEmpty(userRoles)) {
            OwnPermissionVO ownPermissionVO = new OwnPermissionVO();
            ownPermissionVO.setControlPermission(new ArrayList<>());
            ownPermissionVO.setDataPermission(new ArrayList<>());
            return SingleResponse.of(ownPermissionVO);
        }

        // 获取所有角色ID
        List<Long> roleIds = userRoles.stream()
                .map(SysUserRole::getRoleId)
                .collect(Collectors.toList());

        List<Long> enabledIds = sysRoleService.list(Wrappers.<SysRole>lambdaQuery()
                        .in(SysRole::getId, roleIds)
                        .eq(SysRole::getStatus, 1)
                        .select(SysRole::getId))
                .stream().map(SysRole::getId).collect(Collectors.toList());

        // 获取所有角色的权限
        List<RolePermissionEntity> allPermissions = rolePermissionService.list(
                Wrappers.<RolePermissionEntity>lambdaQuery()
                        .in(RolePermissionEntity::getRoleId, enabledIds));

        if (CollectionUtils.isEmpty(allPermissions)) {
            OwnPermissionVO ownPermissionVO = new OwnPermissionVO();
            ownPermissionVO.setControlPermission(new ArrayList<>());
            ownPermissionVO.setDataPermission(new ArrayList<>());
            return SingleResponse.of(ownPermissionVO);
        }

        // 按权限代码分组，计算每个权限的并集
        Map<String, List<RolePermissionEntity>> permissionByCode = allPermissions.stream()
                .filter(Objects::nonNull)
                .filter(p -> p.getPermissionCode() != null)
                .collect(Collectors.groupingBy(RolePermissionEntity::getPermissionCode));

        List<OwnPermissionVO.ControlPermissionVo> controlPermissions = new ArrayList<>();

        for (Map.Entry<String, List<RolePermissionEntity>> entry : permissionByCode.entrySet()) {
            String permissionCode = entry.getKey();
            List<RolePermissionEntity> permissions = entry.getValue();

            // 并集逻辑：只要有任何一个角色拥有该权限，用户就拥有该权限
            OwnPermissionVO.ControlPermissionVo controlPermission = buildControlPermissionUnion(permissionCode, permissions);
            if (controlPermission != null) {
                controlPermissions.add(controlPermission);
            }
        }

        // 获取数据权限
        List<OwnPermissionVO.DataPermissionVo> dataPermissions = buildDataPermissionUnion(currentUser.getEmployeeId(), enabledIds);

        OwnPermissionVO ownPermissionVO = new OwnPermissionVO();
        ownPermissionVO.setControlPermission(controlPermissions);
        ownPermissionVO.setDataPermission(dataPermissions);

        return SingleResponse.of(ownPermissionVO);
    }

    /**
     * 构建单个权限的并集，取权限范围最大的
     *
     * @param permissionCode 权限代码
     * @param permissions    该权限的所有实例
     * @return 权限并集结果
     */
    private OwnPermissionVO.ControlPermissionVo buildControlPermissionUnion(String permissionCode, List<RolePermissionEntity> permissions) {
        if (CollectionUtils.isEmpty(permissions)) {
            return null;
        }

        OwnPermissionVO.ControlPermissionVo controlPermissionVo = new OwnPermissionVO.ControlPermissionVo();
        controlPermissionVo.setPermissionCode(permissionCode);

        // 获取权限操作类型的描述
        PermissionActionType actionType = PermissionActionType.getByCode(permissionCode);
        String permissionName = actionType != null ? actionType.getDescription() : permissionCode;
        controlPermissionVo.setName(permissionName);

        // 处理权限范围，取最大权限
        PermissionScopeType maxScopeType = getMaxScopeType(permissions);
        controlPermissionVo.setScope(maxScopeType != null ? maxScopeType.getCode() : null);

        // 处理权限选项的并集
        List<OwnPermissionVO.Permission> permissionDetails = buildPermissionOptionsUnion(permissions, maxScopeType);
        controlPermissionVo.setPermission(permissionDetails);

        return controlPermissionVo;
    }

    /**
     * 获取最大权限范围类型
     * 优先级：ALL > MULTIPLE > SINGLE
     */
    private PermissionScopeType getMaxScopeType(List<RolePermissionEntity> permissions) {
        Set<String> scopeTypes = permissions.stream()
                .map(RolePermissionEntity::getScope)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());

        // 按优先级返回最大权限范围
        if (scopeTypes.contains(PermissionScopeType.ALL.getCode())) {
            return PermissionScopeType.ALL;
        } else if (scopeTypes.contains(PermissionScopeType.MULTIPLE.getCode())) {
            return PermissionScopeType.MULTIPLE;
        } else if (scopeTypes.contains(PermissionScopeType.SINGLE.getCode())) {
            return PermissionScopeType.SINGLE;
        }
        return null;
    }

    /**
     * 构建权限选项的并集
     */
    private List<OwnPermissionVO.Permission> buildPermissionOptionsUnion(List<RolePermissionEntity> permissions, PermissionScopeType maxScopeType) {
        if (maxScopeType == PermissionScopeType.ALL) {
            // 全部权限，scope为all时没有permission_value字段值，返回所有可能的选项
            return null;
        }

        if (maxScopeType == PermissionScopeType.SINGLE) {
            // 单选权限，要获取所有value值中范围最大的
            return getSingleMaxOption(permissions);
        } else if (maxScopeType == PermissionScopeType.MULTIPLE) {
            // 多选权限，取其并集，将所有的包含项都选择上
            return getMultipleUnionOptions(permissions);
        }

        return new ArrayList<>();
    }

    /**
     * 处理单选权限，从所有角色的permission_value中选择范围最大的
     */
    private List<OwnPermissionVO.Permission> getSingleMaxOption(List<RolePermissionEntity> permissions) {
        Set<String> allSingleOptions = new HashSet<>();

        // 收集所有单选权限的选项
        for (RolePermissionEntity permission : permissions) {
            if (PermissionScopeType.SINGLE.getCode().equals(permission.getScope())
                    && permission.getPermissionValue() != null) {
                String[] options = permission.getPermissionValue().split(",");
                for (String option : options) {
                    if (option != null && !option.trim().isEmpty()) {
                        allSingleOptions.add(option.trim());
                    }
                }
            }
        }

        // 按优先级返回范围最大的选项
        return getMaxSingleOption(allSingleOptions);
    }

    /**
     * 处理多选权限，取所有角色的permission_value的并集
     */
    private List<OwnPermissionVO.Permission> getMultipleUnionOptions(List<RolePermissionEntity> permissions) {
        Set<String> unionOptions = new HashSet<>();

        // 收集所有权限值的并集
        for (RolePermissionEntity permission : permissions) {
            if (permission.getPermissionValue() != null) {
                String[] options = permission.getPermissionValue().split(",");
                for (String option : options) {
                    if (option != null && !option.trim().isEmpty()) {
                        unionOptions.add(option.trim());
                    }
                }
            }
        }

        // 转换为结果格式
        List<OwnPermissionVO.Permission> result = new ArrayList<>();
        for (String optionCode : unionOptions) {
            PermissionOptionType optionType = PermissionOptionType.getByCode(optionCode);
            if (optionType != null) {
                OwnPermissionVO.Permission permission = new OwnPermissionVO.Permission();
                permission.setCode(optionType.getCode());
                permission.setName(optionType.getDescription());
                result.add(permission);
            }
        }

        return result;
    }

    /**
     * 获取权限范围最大的单选选项
     * 优先级：allContract > contractAgent > myContract
     */
    private List<OwnPermissionVO.Permission> getMaxSingleOption(Set<String> options) {
        List<OwnPermissionVO.Permission> result = new ArrayList<>();

        // 按优先级检查选项
        String[] priorityOrder = {
                PermissionOptionType.ALL_CONTRACT.getCode(),
                PermissionOptionType.CONTRACT_AGENT.getCode(),
                PermissionOptionType.MY_CONTRACT.getCode(),
                PermissionOptionType.CONTRACT_LEDGER.getCode(),
                PermissionOptionType.APPROVAL_RECORD.getCode(),
                PermissionOptionType.ARCHIVE_MAIN.getCode(),
                PermissionOptionType.ARCHIVE_ATTACHMENT.getCode()
        };

        for (String optionCode : priorityOrder) {
            if (options.contains(optionCode)) {
                PermissionOptionType optionType = PermissionOptionType.getByCode(optionCode);
                if (optionType != null) {
                    OwnPermissionVO.Permission permission = new OwnPermissionVO.Permission();
                    permission.setCode(optionType.getCode());
                    permission.setName(optionType.getDescription());
                    result.add(permission);
                    break; // 单选只取一个最大权限的选项
                }
            }
        }

        return result;
    }

    /**
     * 构建数据权限的并集
     *
     * @param employeeId 当前用户ID
     * @param roleIds    用户拥有的角色ID列表
     * @return 数据权限列表
     */
    private List<OwnPermissionVO.DataPermissionVo> buildDataPermissionUnion(Long employeeId, List<Long> roleIds) {
        try {
            log.debug("开始构建用户 {} 的数据权限，角色ID: {}", employeeId, roleIds);

            // 获取当前用户的部门信息
            List<Long> departmentIds = sysUserDepartmentService.listDepartmentIdsByUserId(employeeId);
            log.debug("用户 {} 的部门ID列表: {}", employeeId, departmentIds);

            List<RoleDataIsolationEntity> allDataPermissions = new ArrayList<>();

            // 1. 查询角色数据权限
            if (!CollectionUtils.isEmpty(roleIds)) {
                List<RoleDataIsolationEntity> rolePermissions = roleDataIsolationService.list(
                        Wrappers.<RoleDataIsolationEntity>lambdaQuery()
                                .in(RoleDataIsolationEntity::getRoleId, roleIds)
                                .eq(RoleDataIsolationEntity::getPermissionStatus, PermissionStatusType.ENABLE)
                );
                log.debug("查询到角色数据权限 {} 条", rolePermissions.size());
                allDataPermissions.addAll(rolePermissions);
            }

            // 2. 查询用户数据权限（userId字段包含当前用户ID）
            List<RoleDataIsolationEntity> userPermissions = getUserDataPermissions(employeeId);
            log.debug("查询到用户数据权限 {} 条", userPermissions.size());
            allDataPermissions.addAll(userPermissions);

            // 3. 查询部门数据权限（departmentId字段包含当前用户的部门ID）
            if (!CollectionUtils.isEmpty(departmentIds)) {
                List<RoleDataIsolationEntity> deptPermissions = getDepartmentDataPermissions(departmentIds);
                log.debug("查询到部门数据权限 {} 条", deptPermissions.size());
                allDataPermissions.addAll(deptPermissions);
            }

            // 4. 过滤有效期内的权限
            Date now = new Date();
            List<RoleDataIsolationEntity> validPermissions = allDataPermissions.stream()
                    .filter(permission -> isDataPermissionValid(permission, now))
                    .collect(Collectors.toList());
            log.debug("有效期内的数据权限记录数: {}", validPermissions.size());

            // 5. 按数据类型分组并计算并集
            Map<DataType, List<RoleDataIsolationEntity>> permissionsByType = validPermissions.stream()
                    .filter(Objects::nonNull)
                    .filter(p -> p.getDataType() != null)
                    .collect(Collectors.groupingBy(RoleDataIsolationEntity::getDataType));

            List<OwnPermissionVO.DataPermissionVo> result = new ArrayList<>();

            // 6. 处理每种数据类型的权限并集
            for (Map.Entry<DataType, List<RoleDataIsolationEntity>> entry : permissionsByType.entrySet()) {
                DataType dataType = entry.getKey();
                List<RoleDataIsolationEntity> permissions = entry.getValue();

                OwnPermissionVO.DataPermissionVo dataPermission = buildDataTypePermissionUnion(dataType, permissions);
                if (dataPermission != null) {
                    result.add(dataPermission);
                }
            }

            log.debug("用户 {} 最终数据权限数量: {}", employeeId, result.size());
            return result;

        } catch (Exception e) {
            log.error("构建用户 {} 数据权限失败", employeeId, e);
            return new ArrayList<>();
        }
    }

    /**
     * 查询用户数据权限（userId字段包含指定用户ID）
     */
    private List<RoleDataIsolationEntity> getUserDataPermissions(Long userId) {
        // 查询所有启用的数据权限，然后在内存中过滤
        List<RoleDataIsolationEntity> allUserPermissions = roleDataIsolationService.list(
                Wrappers.<RoleDataIsolationEntity>lambdaQuery()
                        .eq(RoleDataIsolationEntity::getPermissionStatus, PermissionStatusType.ENABLE)
                        .isNotNull(RoleDataIsolationEntity::getUserId)
        );

        // 在内存中过滤包含当前用户ID的权限
        return allUserPermissions.stream()
                .filter(permission -> {
                    String userIdStr = permission.getUserId();
                    if (userIdStr == null || userIdStr.trim().isEmpty()) {
                        return false;
                    }

                    // 检查userId字段是否包含当前用户ID
                    String[] userIds = userIdStr.split(",");
                    for (String id : userIds) {
                        if (id.trim().equals(userId.toString())) {
                            return true;
                        }
                    }
                    return false;
                })
                .collect(Collectors.toList());
    }

    /**
     * 查询部门数据权限（departmentId字段包含指定部门ID）
     */
    private List<RoleDataIsolationEntity> getDepartmentDataPermissions(List<Long> departmentIds) {
        // 查询所有启用的数据权限，然后在内存中过滤
        List<RoleDataIsolationEntity> allDeptPermissions = roleDataIsolationService.list(
                Wrappers.<RoleDataIsolationEntity>lambdaQuery()
                        .eq(RoleDataIsolationEntity::getPermissionStatus, PermissionStatusType.ENABLE)
                        .isNotNull(RoleDataIsolationEntity::getDepartmentId)
        );

        // 在内存中过滤包含当前用户部门ID的权限
        return allDeptPermissions.stream()
                .filter(permission -> {
                    String deptIdStr = permission.getDepartmentId();
                    if (deptIdStr == null || deptIdStr.trim().isEmpty()) {
                        return false;
                    }

                    // 检查departmentId字段是否包含当前用户的任一部门ID
                    String[] deptIds = deptIdStr.split(",");
                    for (String deptId : deptIds) {
                        String trimmedDeptId = deptId.trim();
                        for (Long userDeptId : departmentIds) {
                            if (trimmedDeptId.equals(userDeptId.toString())) {
                                return true;
                            }
                        }
                    }
                    return false;
                })
                .collect(Collectors.toList());
    }

    /**
     * 检查数据权限是否在有效期内
     */
    private boolean isDataPermissionValid(RoleDataIsolationEntity permission, Date now) {
        // 永久有效
        if (ValidityType.PERMANENT.equals(permission.getValidityType())) {
            return true;
        }

        // 固定期限
        if (ValidityType.FIXED_DATE.equals(permission.getValidityType())) {
            Date startDate = permission.getValidityStartDate();
            Date endDate = permission.getValidityEndDate();

            if (startDate != null && endDate != null) {
                return !now.before(startDate) && !now.after(endDate);
            }
        }

        return false;
    }

    /**
     * 构建单一数据类型的权限并集
     */
    private OwnPermissionVO.DataPermissionVo buildDataTypePermissionUnion(DataType dataType, List<RoleDataIsolationEntity> permissions) {
        if (CollectionUtils.isEmpty(permissions)) {
            return null;
        }

        // 获取最高权限范围
        ContractScopeTypeEnums maxScope = getMaxDataPermissionScope(permissions);
        if (maxScope == null) {
            return null;
        }

        OwnPermissionVO.DataPermissionVo dataPermission = new OwnPermissionVO.DataPermissionVo();
        
        // 设置权限编码和名称
        String permissionCode = dataType.name();
        dataPermission.setCode(permissionCode);
        dataPermission.setName(getDataTypeDescription(dataType));
        
        // 设置权限范围
        dataPermission.setScope(maxScope.name());
        dataPermission.setDescription(getDataScopeDescription(dataType, maxScope));

        return dataPermission;
    }

    /**
     * 获取最大数据权限范围
     * 优先级：ALL > DEPARTMENT > CUSTOM
     */
    private ContractScopeTypeEnums getMaxDataPermissionScope(List<RoleDataIsolationEntity> permissions) {
        Set<ContractScopeTypeEnums> scopes = permissions.stream()
                .map(RoleDataIsolationEntity::getContractScope)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());

        // 按优先级返回最大权限范围
        if (scopes.contains(ContractScopeTypeEnums.ALL)) {
            return ContractScopeTypeEnums.ALL;
        } else if (scopes.contains(ContractScopeTypeEnums.DEPARTMENT)) {
            return ContractScopeTypeEnums.DEPARTMENT;
        } else if (scopes.contains(ContractScopeTypeEnums.CUSTOM)) {
            return ContractScopeTypeEnums.CUSTOM;
        }
        return null;
    }

    /**
     * 获取数据类型的描述
     */
    private String getDataTypeDescription(DataType dataType) {
        switch (dataType) {
            case CONTRACT:
                return "合同数据权限";
            case NEGOTIATION:
                return "协商数据权限";
            default:
                return dataType.name() + "数据权限";
        }
    }

    /**
     * 获取数据权限范围的描述
     */
    private String getDataScopeDescription(DataType dataType, ContractScopeTypeEnums scope) {
        String dataTypeName = dataType == DataType.CONTRACT ? "合同" : "审核";
        
        switch (scope) {
            case ALL:
                return "全部" + dataTypeName;
            case DEPARTMENT:
                return "部门" + dataTypeName;
            case CUSTOM:
                return "自定义" + dataTypeName;
            default:
                return scope.name() + dataTypeName;
        }
    }

    private String generateRandomAlphaString(int length) {
        // 定义大写英文字母字符集
        String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        StringBuilder result = new StringBuilder(length);
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            int randomIndex = random.nextInt(characters.length());
            result.append(characters.charAt(randomIndex));
        }
        return result.toString();
    }
} 